package conf

import (
	"code.simon.com/data-agent/common"
	"encoding/json"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/sirupsen/logrus"
	"net/url"
	"strconv"
	"strings"
)

// 创建serverConfig
var serverConfigs []constant.ServerConfig
var configClient config_client.IConfigClient
var clientConfig constant.ClientConfig

func InitNacos() {
	// 创建clientConfig
	clientConfig = constant.ClientConfig{
		NamespaceId:         ConfigObj.NacosConfig.NamespaceId,
		TimeoutMs:           ConfigObj.NacosConfig.TimeoutMs,
		NotLoadCacheAtStart: ConfigObj.NacosConfig.NotLoadCacheAtStart,
		LogDir:              ConfigObj.NacosConfig.LogDir,
		CacheDir:            ConfigObj.NacosConfig.CacheDir,
		RotateTime:          ConfigObj.NacosConfig.RotateTime,
		MaxAge:              ConfigObj.NacosConfig.MaxAge,
		LogLevel:            ConfigObj.NacosConfig.LogLevel,
	}
	// 根据配置文件
	for _, ipAdder := range strings.Split(ConfigObj.NacosConfig.IpAdders, ",") {
		urlObj, err := url.Parse(ipAdder)
		if err != nil {
			panic(err)
		}
		host := strings.Split(urlObj.Host, ":")
		port, _ := strconv.Atoi(host[1])
		serverConfigs = append(serverConfigs, *constant.NewServerConfig(
			host[0],
			uint64(port),
			constant.WithScheme(urlObj.Scheme),
			constant.WithContextPath(urlObj.Path[1:]),
		))
	}
	// 创建动态配置客户端
	configClient, _ = clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	// 获取配置
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: getNacosDataId(),
		Group:  ConfigObj.NacosConfig.Group})
	if len(content) == 0 {
		// 之前没有配置则发布默认配置
		data, err := json.Marshal(ConfigObj)
		if err != nil {
			logrus.Error("json marshal failed")
			return
		}
		logrus.Println("json:%s\n", data)
		_, err = configClient.PublishConfig(vo.ConfigParam{
			DataId:  getNacosDataId(),
			Group:   ConfigObj.NacosConfig.Group,
			Content: string(data)})
		if err != nil {
			panic(err)
		}

	} else {
		// 覆盖本地配置
		err = json.Unmarshal([]byte(content), ConfigObj)
		if err != nil {
			panic(err)
		}

	}
	ListenNacosConfig()
}

// ListenNacosConfig 监听nacos配置变化
func ListenNacosConfig() {
	err := configClient.ListenConfig(vo.ConfigParam{
		DataId: getNacosDataId(),
		Group:  ConfigObj.NacosConfig.Group,
		OnChange: func(namespace, group, dataId, data string) {
			//logrus.Printf("server publish config, group:%s ,dataId:%s ,data:%s", group, dataId, data)
			//// 停止所有task
			//for _, task := range gotail.TailMsg.TailTaskMsrMap {
			//	task.Cancel()
			//}
			//err := json.Unmarshal([]byte(data), ConfigObj)
			//common.HandleError(err)
			////gotail.InitTail()
			//logrus.Println(gotail.TailMsg.TailTaskMsrMap)
		},
	})
	common.HandleError(err)
	logrus.Println("nacos: start listen config")
}

func getNacosDataId() (dataId string) {
	if ConfigObj.NacosConfig.FocusConfig {
		dataId = ConfigObj.NacosConfig.DataId
	} else   {
		dataId = common.GetLocalIp()
	}
	return
}
